#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

# for printing records to page

import re
from terms import *
from urlcheck import *
from util import *
from oaicookie import *
from dbinter import *

# take a string from a dict and put it in a list if it exists
def appStr(sDict, sKey):
	if sDict.has_key(sKey) and len(sDict[sKey].strip()) > 0:
		return [sDict[sKey].strip()]
	return []

# check to see if it is an empty string after trimming
def notEmpty(field, fLen = 0):
	if len(field.strip()) > fLen:
		return 1
	return 0

# generate a tracking url for a result click
def makeTrackUrl(url,recHash,terms):
	if notEmpty(url):
		return "/url.py?s=%s&i=%s&u=%s" \
			% (urls(terms),recHash,urls(url))
	else:
		return ''

# print out a title
def outTitle(title,url,termlist = [],maxLen = 80):
	title = shorten(title,maxLen)
	if len(title) < 1:
		title = '[No Title]'
	# if expanded (no max length) allow linebreaks
	if maxLen == 0: title = title.replace('\n','<br>')

	title = boldify(title,termlist)
	if len(url) > 0:
		title = "<a href=\"%s\">%s</a>" % (url, title)
	print chkenc(title)

# print out dynamic record actions
def outActions(recHash, resNum, escapedTerms, expand = 1):
	# escape singlequote
	escapedTerms = escapedTerms.replace(r"'",r"\'")
	resNum = str(resNum)
	if len(resNum) <= 2:
		resNum = 'res' + resNum
	if expand == 1:
		# expand with full metadata
		print "&nbsp; <a title=\"View Full Metadata\" onClick=\"sendExpand('%s','%s','%s');\"><span class=\"details\">Expand</span></a>" % (recHash, resNum, escapedTerms)
	else:
		# shrink to shortened result
		print "<a title=\"View Abreviated Metadata\"onClick=\"sendShrink('%s','%s','%s');\"><span class=\"details\">Shrink</span></a>" % (recHash, resNum, escapedTerms)
	print \
"""
<![if gt IE 7]>&nbsp; <a onClick=\"addTab('%s'); rememberTab('%s'); sendRemember(); checkMove(0);\"><span class=\"details\">Remember</span></a><![endif]>
""" % (recHash,recHash)

	# select to suggest a place in the directory, or call up for review
	if expand == 0:

		inDir = len(quick_query('SELECT * FROM directoryTree WHERE recHash = \'%s\';' % recHash))
		if inDir == 0:
			print '&nbsp; <a title="Suggest a place for this record in the directory." href="suggest.py?r=%s" class="noul" onclick="rememberLocation();"><span class="details">Suggest</span></a>' % (recHash)
		else:
			print '&nbsp; <a title="View this entry in the directory." href="index.py?d=%s&vp=1" class="noul"><span class="details">Directory</span></a>' % (recHash)
		
	print '<br>'

# print out dynamic remember record actions
def outRememberActions(rechash):
	if isHashForgotten(rechash):
		print '<a onClick="rememberTab(\'%s\'); sendRemember();"><span class="details">Remember</span></a>' % (rechash)
	else:
		print '<a onClick="forgetTab(\'%s\'); sendRemember();"><span class="details">Forget</span></a>' % (rechash)

# print out the creator
def outCreator(creator, termlist, maxLen = 60):
	nlMatch = re.compile('\n|;')
	# check for empty field w/ newlines
	if nlMatch.sub('',creator).strip() == '': return 0
	# minimum length
	min = 0
	if maxLen > 3: min = 3
	# standardize delimiters
	creator = shorten(nlMatch.sub('; ',creator.strip()),maxLen, min)
	if len(creator) > 0:
		# if there is a single creator
		if nlMatch.search(creator) is None:
			# print out an author quick search
			qas = '<a class=\"noUL\" href=/search.py?s=author:\"%s\">&#9658;</a>' % (urls(creator))
			print chkenc(qas)
		creator = "<i>%s</i>" % boldify(creator,termlist)
		print chkenc(creator)
		# printed creator
		return 1
	else:
		# didn't print creator
		return 0

# print out the subject
def outSubject(subject, termlist, noNewLine = 0, maxLen = 60):
	subject = shorten(subject.strip(),maxLen)
	# handle newlines
	if maxLen == 0:
		# expanded form
		subject = subject.replace('\n','<br>')
	if notEmpty(subject):
		subject = boldify(subject,termlist)
		if noNewLine == 1:
			subject = " - <span class='grey'>%s</span>" % subject
		else:
			subject = "<span class='grey'>%s</span>" % subject
		print chkenc(subject)
		# printed subject
		return 1
	else:
		# didn't print subject
		return 0

# print out the description
def outDescription(description, termlist, maxLen = 400):
	min = 0
	if maxLen > 10: min = 10
	description = shorten(description.strip(),maxLen, min)
	if notEmpty(description):
		description = "%s <br>" % boldify(description,termlist)
		description = linkify(description)
		# if expanded (no max length) allow breaks
		if maxLen == 0: description = description.replace('\n','<br>')
		print chkenc(description)

# print out the footer - url and date
def outFooter(url,title,datestamp):
	print "<span class=\"greenify\""
	# if there was no valid url found, allow for a google scholar search
	if url == '':
		google = bad_url(title)
		googleScholar = ">%s" \
			% ('<a href=\"http://scholar.google.com/scholar?q=%22' \
			+ urls(google) + '%22\">Search Google Scholar</a>')
		print chkenc(googleScholar)
		# also normal google search
		googleNormal = "&nbsp;&nbsp;<a href=\"%s\">Search Google</a>" \
			% ('http://www.google.com/search?q=%22' + urls(google) + '%22')
		print chkenc(googleNormal)
	else:
		print ">%s" % (url)
	# shorten to date only if needed
	if notEmpty(datestamp):
		shDt = re.compile ('(.+)(T.*)$')
		dateMan = shDt.search(datestamp)
		if dateMan is not None:
			datestamp = dateMan.groups()[0]
		print " &nbsp;-&nbsp; %s"  % datestamp
	print '</span>'

# print out a record in short form
def print_rec_short(results,terms,resnum):
	# generate the terms list
	th = terms_handler(terms)
	termlist = th.get_terms()

	# find the url and generate the tracking url
	validUrl = checkUrl(results,1)
	trackUrl = makeTrackUrl(urls(validUrl),results['recHash'],urls(terms))

	# print out the title
	outTitle(results['mTitle'],trackUrl,termlist['keywords'] + appStr(termlist,'mTitle'))

	print "<font size=\"-1\">"
	
	# print out dynamic result actions
	outActions(results['recHash'], resnum, urls(terms))
	
	# print out the creator
	creator = outCreator(results['mCreator'], termlist['keywords'] + appStr(termlist,'mCreator'))
	
	# print out the subject
	subject = outSubject(results['mSubject'], termlist['keywords'] + appStr(termlist,'mSubject'), creator)

	# print break only if needed
	if creator + subject > 0:
		print '<br>'

	# print out the description
	outDescription(results['mDescription'],termlist['keywords'] + appStr(termlist,'mDescription'))

	# print out the footer - url and date
	outFooter(validUrl,results['mTitle'],results['hDatestamp'])

	print "</font>"

# print out a field for expanded record print
def expanded_form(label,field):
	if notEmpty(field):
		print '<tr><td class="expand_bg">%s:</td>' % label
		field = linkify(field)
		field = field.replace('\n','<br>')
		field = '<td>%s</td></tr>' % field
		print chkenc(field)

# print out a record in expanded form
def print_rec_expand(results,terms,resnum):
	# generate the terms list
	th = terms_handler(terms)
	termlist = th.get_terms()

	# find the url and generate the tracking url
	validUrl = checkUrl(results,1)
	trackUrl = makeTrackUrl(urls(validUrl),results['recHash'],urls(terms))

	# table format
	print '<table border="0" class="smallish">'

	# print out the title
	print '<tr><td class="expand_bg">Title:</td><td>'
	outTitle(results['mTitle'],trackUrl,termlist['keywords'] + appStr(termlist,'mTitle'),0)
	print '</td></tr>'

	
	# print out dynamic result actions
	print '<tr><td class="expand_bg">Actions:</td><td>'
	outActions(results['recHash'], resnum, urls(terms),0)
	print '</td></tr>'
	
	# print out the creator
	if notEmpty(results['mCreator']):
		print '<tr><td class="expand_bg">Creator/Author:</td><td>'
		creator = outCreator(results['mCreator'], termlist['keywords'] + appStr(termlist,'mCreator'),0)
		print '</td></tr>'
	
	# print out the subject
	if notEmpty(results['mSubject']):
		print '<tr><td class="expand_bg">Subject:</td><td>'
		subject = outSubject(results['mSubject'], termlist['keywords'] + appStr(termlist,'mSubject'), 0,0)
		print '</td></tr>'

	# print out the publisher
	expanded_form('Publisher',results['mPublisher'])
	
	# print out the contributor
	expanded_form('Contributor(s)',results['mContributor'])
	
	# print out the repository
	expanded_form('Repository',results['iRepository'])

	# print out the document date
	expanded_form('Date',results['mDate'])

	# print out the description
	if notEmpty(results['mDescription']):
		print '<tr><td class="expand_bg">Description:</td><td>'
		outDescription(results['mDescription'],termlist['keywords'] + appStr(termlist,'mDescription'),0)
		print '</td></tr>'

	# print out the rights
	expanded_form('Rights',results['mRights'])
		
	# print out the type
	expanded_form('Type',results['mType'])

	# print out the relation
	expanded_form('Relation',results['mRelation'])

	# print out the coverage
	expanded_form('Coverage',results['mCoverage'])

	# print out the language
	expanded_form('Language',results['mLanguage'])

	# print out the source
	expanded_form('Source',results['mSource'])

	# print out the format
	expanded_form('Format',results['mFormat'])

	# print out identifier 1
	expanded_form('Identifier 1',results['hIdentifier'])

	# print out identifier 2
	expanded_form('Identifier 2',results['mIdentifier'])

	# print out the url
	print '<tr><td class="expand_bg">URL:</td><td>'
	outFooter(validUrl,results['mTitle'],'')
	print '</td></tr>'

	# print out last updated
	if notEmpty(results['hDatestamp']):
		print '<tr><td class="expand_bg">Last&nbsp;Modified:</td><td>'
		print '<span class="greenify">%s</span>' % results['hDatestamp']
		print '</td></tr>'

	print '</table>'

# print out a record in expanded form
def print_rec_remember(results):
	# find the url and generate the tracking url
	validUrl = checkUrl(results,1)
	trackUrl = makeTrackUrl(urls(validUrl),results['recHash'],'')

	# table format
	print '<table border="0" class="smallish">'

	# print out the title
	print '<tr><td class="expand_bg">Title:</td><td>'
	outTitle(results['mTitle'],trackUrl,[],0)
	print '</td></tr>'

	# remember actions
	print '<tr><td class="expand_bg">Actions:</td><td>'
	outRememberActions(results['recHash'])
	print '</td></tr>'

	# print out the creator
	if notEmpty(results['mCreator']):
		print '<tr><td class="expand_bg">Creator/Author:</td><td>'
		creator = outCreator(results['mCreator'], [],0)
		print '</td></tr>'
	
	# print out the subject
	if notEmpty(results['mSubject']):
		print '<tr><td class="expand_bg">Subject:</td><td>'
		subject = outSubject(results['mSubject'], [], 0,0)
		print '</td></tr>'

	# print out the publisher
	expanded_form('Publisher',results['mPublisher'])
	
	# print out the contributor
	expanded_form('Contributor(s)',results['mContributor'])
	
	# print out the repository
	expanded_form('Repository',results['iRepository'])

	# print out the document date
	expanded_form('Date',results['mDate'])

	# print out the description
	if notEmpty(results['mDescription']):
		print '<tr><td class="expand_bg">Description:</td><td>'
		outDescription(results['mDescription'],[],0)
		print '</td></tr>'

	# print out the rights
	expanded_form('Rights',results['mRights'])
		
	# print out the type
	expanded_form('Type',results['mType'])

	# print out the relation
	expanded_form('Relation',results['mRelation'])

	# print out the coverage
	expanded_form('Coverage',results['mCoverage'])

	# print out the language
	expanded_form('Language',results['mLanguage'])

	# print out the source
	expanded_form('Source',results['mSource'])

	# print out the format
	expanded_form('Format',results['mFormat'])

	# print out identifier 1
	expanded_form('Identifier 1',results['hIdentifier'])

	# print out identifier 2
	expanded_form('Identifier 2',results['mIdentifier'])

	# print out the url
	print '<tr><td class="expand_bg">URL:</td><td>'
	outFooter(validUrl,results['mTitle'],'')
	print '</td></tr>'

	# print out last updated
	if notEmpty(results['hDatestamp']):
		print '<tr><td class="expand_bg">Last&nbsp;Modified:</td><td>'
		print '<span class="greenify">%s</span>' % results['hDatestamp']
		print '</td></tr>'

	print '</table>'

# eof

